<template>
    <div class="payment-card-page">
        <!-- 页面头部 -->
        <TopNav
                title="选择课程"
                :showBack="true"
                :showAdd="false"
        />
        <!-- 表单区域 -->
        <van-form
                label-align="top"
                @submit="handleSubmit"
                @failed="handleFormError"
                class="payment-form"
        >

            <!-- 课程名称 -->
            <van-field
                    disabled
                    v-model="formData.productName"
                    name="productName"
                    :rules="[{ required: true, message: '请输入课程名称' }]"
                    class="form-field"
                    placeholder="请输入课程名称"
            >
                <template #label>
                    <span class="normal-label">课程名称<span class="required">*</span></span>
                </template>
            </van-field>

            <!-- 课程金额 -->
            <van-field
                    :disabled="formData.orderPriceEdit != 1"
                    v-model="formData.price"
                    name="price"
                    :rules="[{ required: true, message: '请输入课程金额' }]"
                    class="form-field"
                    placeholder="请输入课程金额"
                    @input="onPriceInput"
            >
                <template #label>
                    <span class="normal-label">课程金额<span class="required">*</span></span>
                </template>
            </van-field>

            <!-- 培训周期 -->
            <van-field
                    disabled
                    v-model="formData.trainingPeriod"
                    name="trainingPeriod"
                    :rules="[{ required: true, message: '请输入培训周期' }]"
                    class="form-field"
                    placeholder="请输入培训周期"
            >
                <template #label>
                    <span class="normal-label">培训周期<span class="required">*</span></span>
                </template>
            </van-field>


            <!-- 授课方式 -->
            <van-field
                    disabled
                    v-model="formData.teachingMethod"
                    name="teachingMethod"
                    :rules="[{ required: true, message: '请输入课程金额' }]"
                    class="form-field"
                    placeholder="请输入授课方式"
            >
                <template #label>
                    <span class="normal-label">授课方式<span class="required">*</span></span>
                </template>
            </van-field>

            <!-- 付款次数 -->
            <van-field
                    v-if="formData.payType ==='10'"
                    v-model="formData.installmentName"
                    name="installment"
                    placeholder="请选择付款次数"
                    :rules="[{ required: true, message: '请选择付款次数' }]"
                    readonly
                    is-link
                    clickable
                    @click="showPicker = true"
                    class="form-field"
            >
                <template #label>
                    付款次数<span class="required"> *</span>
                </template>
            </van-field>

            <!-- 付款次数 -->
            <van-field
                    v-if="formData.payType ==='20'"
                    disabled
                    v-model="payTypeText"
                    name="trainingPeriod"
                    class="form-field"
            >
                <template #label>
                    <span class="normal-label">付款次数<span class="required">*</span></span>
                </template>
            </van-field>


            <!-- 付款计划 -->
            <van-field
                    v-if="formData.payType ==='10'"
                    name="installment"
                    placeholder="查看付款计划"
                    readonly
                    is-link
                    clickable
                    @click="showPlan"
                    class="form-field"
            >
                <template #label>
                    付款计划<span class="required"> *</span>
                </template>
            </van-field>


            <!-- 提交按钮 -->
            <div class="form-actions">
                <MyButton text="立即报名" />
            </div>
        </van-form>


        <van-action-sheet
                v-model:show="showPicker"
                :actions="formData.installmentCovertArr"
                @select="onSelect"
        />

        <!-- ActionSheet -->
        <van-action-sheet
                v-model:show="show"
                title="标题"
        >
            <div style="padding: 16px;">
                <div class="payment-plan">
                    <h3 class="title">付款计划</h3>

                    <van-steps direction="vertical" :active="-1">
                        <van-step v-for="(item, index) in planMap[formData.installment]" :key="index">
                            <div class="plan-item">
                                <div class="plan-header">
                                    <span class="phase">第{{ index + 1 }}期</span>
                                    <span class="amount">¥{{ item.price }}元</span>
                                </div>
                                <div class="plan-date">支付日期：{{ item.date }}</div>
                            </div>
                        </van-step>
                    </van-steps>
                </div>
            </div>
        </van-action-sheet>


    </div>
</template>

<script>
    import TopNav from "@/components/TopNav.vue";
    import MyButton from "@/components/MyButton.vue";
    import {useRoute} from 'vue-router';
    import {toast} from '@/utils/toast';
    import {getProductDetail, applyProduct} from '@/api/index.js'


    export default {
        name: 'ApplyProductPage',
        components: {
            TopNav, // 注册
            MyButton
        },

        data() {
            return {
                payTypeText: '一次性付款',
                planMap: {},
                show: false,
                product: {},

                // 表单数据
                formData: {
                    productId: '',
                    productName: '',
                    price: '',
                    trainingPeriod: '',
                    teachingMethod: '',
                    installment: '',
                    installmentName: '',
                    installmentPrice: [],
                    orderPriceEdit: 1,
                    installmentCovertArr: [],
                    payType: ''
                },

                // 弹窗控制
                showPicker: false,

            };
        },
        methods: {
            onSelect(item) {
                console.log(item)
                this.formData.installment = item.value;
                this.formData.installmentName = item.name;
                this.showPicker = false;
            },
            showPlan() {
                if (!this.formData.price) {
                    toast('请先填写金额')
                    return;
                }
                if (!this.formData.installment) {
                    toast('请先选择付款次数')
                    return;
                }
                this.show = true;
            },
            onPriceInput(event) {
                let value = event.target.value;
                // 只允许数字和最多两位小数
                let newValue = value
                    .replace(/[^\d.]/g, '')        // 删除非数字和小数点
                    .replace(/^\./g, '')           // 开头不能是小数点
                    .replace(/\.{2,}/g, '.')       // 连续小数点只保留一个
                    .replace(/^(\d+)\.(\d{0,2}).*$/, '$1.$2'); // 保留两位小数
                this.formData.price = newValue || null;
            },
            // 处理表单提交
            async handleSubmit(values) {
                console.log('表单提交:', values);
                if(this.formData.payType ==='20'){
                    this.formData.installment = '0';
                    this.formData.installmentPrice = [{price:this.formData.price,date:''}]
                }else{
                    this.formData.installmentPrice = this.planMap[this.formData.installment];
                }
                let res = await applyProduct(this.formData);
                if (res.code === 200) {
                    this.formData = {
                        productId: '',
                        productName: '',
                        price: '',
                        trainingPeriod: '',
                        teachingMethod: '',
                        installment: '',
                        installmentName: '',
                        installmentPrice: [],
                        orderPriceEdit: 1,
                        installmentCovertArr: [],
                        payType: ''
                    };
                    this.$router.push(`/userCert/idCard?productId=${this.product.id}`);
                }
            },

            async getProductDetail(productId) {
                const res = await getProductDetail(productId);
                if (res.code == 200) {
                    let product = res.data;
                    if (product) {
                        this.formData = product;
                        this.formData.productName = product.title;
                        this.planMap = product.installmentPriceCoverMap || {};
                        this.product = product;
                    }
                }
            },
        },
        mounted() {
            const route = useRoute();
            let productId = route.query.productId;

            this.getProductDetail(productId)
        }
    };
</script>

<style scoped>
    .payment-card-page {
        background-color: #f5f5f5;
        min-height: 100vh;
    }

    .page-header {
        background-color: #ffffff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    .payment-form {
        background-color: #ffffff;
        margin-top: 10px;
        padding: 0 16px;
    }

    .card-type-group {
        display: flex;
        padding: 16px 0;
        border-bottom: 10px solid #eee;
    }

    .card-type-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .card-icon {
        margin-right: 8px;
        color: #1989fa;
    }

    .form-field {
        border-bottom: 1px solid #eee;
    }

    .form-actions {
        padding: 16px;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }



    .cancel-btn {
        background-color: transparent;
        color: #666;
    }

    .bank-picker-popup {
        width: 100%;
    }

    .required {
        color: red;
        margin-right: 4px;
    }


    /* 确保光标在移动端居中 */
    .van-search__field {
        height: 36px;
        line-height: 36px;
    }

    .van-search__input {
        height: 100%;
        line-height: 36px;
        font-size: 16px;
        padding: 0 10px;
    }

    .payment-plan {
        padding: 16px;
        background: #fff;
        margin-top: -38px;
    }

    .title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 12px;
    }

    .plan-item {
        display: flex;
        flex-direction: column;
    }

    .plan-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
    }

    .phase {
        font-weight: 500;
        color: #333;
    }

    .amount {
        color: #f56c6c;
        font-weight: bold;
    }

    .plan-date {
        font-size: 12px;
        color: #999;
    }

    .normal-label {
        color: #333;
    }


</style>
